<template>
    
    <el-button @click="beginAvatarUpdate(7, null)">修改存档照片</el-button>
    <el-dialog v-model="avatarUpload.isEdit">
        <el-upload v-if="avatarUpload.isEdit" accept=".png,.jpg" action="/student/avatarupload" name="avatar"
            :headers="avatarUpload.headers" list-type="picture-card" :on-success="uploadSuccessHandler"
            :before-upload="beforeUploadHandler" :file-list="avatarUpload.fileList">
            选择图片
            <template #tip>
                <div style="color: red; padding: 10px 0">
                    请上传png/jpg文件,且小于2Mb
                </div>
            </template>
        </el-upload>
        <el-button @click="avatarUpdate" :disabled="avatarUpload.model.stu_avatar_new === null">存档</el-button>
        <el-button @click="avatarUpload.isEdit = false">取消</el-button>
    </el-dialog>
</template>
<script setup lang="ts">
import { ElMessage } from "element-plus";
import type { UploadFile, UploadFiles, UploadRawFile, UploadUserFile } from "element-plus";
import { nextTick, reactive } from "vue";
import { StudentApi } from "@/api";

const avatarUpload = reactive<{
    isEdit: boolean;
    headers: Headers | Record<string, any>;
    model: HttpPayload.StudentAvatarUpdate;
    fileList: Array<UploadUserFile>
}>({
    isEdit: false,
    headers: { Authorization: sessionStorage.getItem("token") },
    model: { stu_id: 0, stu_avatar_old: null, stu_avatar_new: null },
    fileList: []
});

const uploadSuccessHandler = (
    res: any,
    file: UploadFile,
    fileList: UploadFiles
) => {
    avatarUpload.model.stu_avatar_new = res.data;
    if (fileList.length > 1) fileList.shift();
};
const beforeUploadHandler = (file: UploadRawFile) => {
    if (file.type !== "image/jpeg" && file.type !== "image/png") {
        ElMessage.error("存档图片必须是jpg/png格式");
        return false;
    } else if (file.size / 1024 / 1024 > 2) {
        ElMessage.error("图片必须小于2mb");
        return false;
    }
    return true;
};
const beginAvatarUpdate = async (
    stu_id: number,
    stu_avatar_old: string | null
) => {
    avatarUpload.model.stu_id = stu_id;
    avatarUpload.model.stu_avatar_old = stu_avatar_old;
    avatarUpload.model.stu_avatar_new = null;
    avatarUpload.fileList.splice(0, avatarUpload.fileList.length);
    if (stu_avatar_old !== null) {
        avatarUpload.fileList.push({
            name: stu_avatar_old,
            url: stu_avatar_old
        })

    }
    nextTick(() => (avatarUpload.isEdit = true));
};

const avatarUpdate = async () => {
    const newAvatarPath = await StudentApi.avatarUpdate(avatarUpload.model);
    //更新学生列表数据，此处无法实现，因为这是一个专讲上传的demo,没有学生列表
    ElMessage.success("图片存档成功...");
    avatarUpload.isEdit = false;
};
</script>
<style scoped lang="stylus"></style>
  